/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Business;

import DataAccess.LoginDataAccess;
import Entities.UserEntities;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.jms.Session;
import javax.servlet.http.HttpSession;

/**
 *
 * @author vjphl
 */
@ManagedBean
@RequestScoped
public class LoginBean {

    UserEntities userEntities;
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
    private String userLogin;

    /**
     * Creates a new instance of LoginBean
     */
    public LoginBean() {
        userEntities = new UserEntities();
        
        
        //checkSession();
    }
    
    public void checkLogin()
    {
        try {
            LoginDataAccess loginDataAccess = new LoginDataAccess();
            
            if (loginDataAccess.CheckLogin(userEntities)) {
                userLogin = userEntities.getUserName();
                session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
                session.setAttribute("userID", userEntities.getUserName());
                userLogin = userEntities.getUserName();
                FacesContext.getCurrentInstance().getExternalContext().redirect("../Admin/Index.xhtml");
                
            }
            else{
                FacesMessage error = new FacesMessage("Login False");
                FacesContext.getCurrentInstance().addMessage(null, error);
                FacesContext.getCurrentInstance().getExternalContext().redirect("../Admin/Login.xhtml");
            }
        } catch (Exception ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void checkSession(){
        try {
            if(session == null){
                FacesContext.getCurrentInstance().getExternalContext().redirect("../Admin/Login.xhtml");
                session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
                session.setAttribute("userID", "");
            }
        } catch (IOException ex) {
                Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    public UserEntities getUserEntities() {
        return userEntities;
    }

    public void setUserEntities(UserEntities userEntities) {
        this.userEntities = userEntities;
    }
    
    public String getUserLogin() {
        return userLogin;
    }

    public void setUserLogin(String userLogin) {
        this.userLogin = userLogin;
    }
}
